import React, { useState } from 'react';
import { request, useRequest } from 'ice';
import {
  Card,
  Table,
  Pagination,
  Divider,
  ResponsiveGrid,
  Button,
  Box,
  Form,
  Field,
  Input,
  Loading,
  Message,
  Dialog,
  Tag,
  Icon,
} from '@alifd/next';

import DialogOperation, { OperationProps } from './DialogOperation';
import DialogCast, { CastProps } from './DialogCast';

import styles from './index.module.scss';

const TableList: React.FunctionComponent = (): JSX.Element => {
  const limit = 5;
  const [page, setPage] = useState(1);
  const [sort, setSort] = useState({
    field: 'createAt',
    order: 'desc',
  });
  const [filter, setFilter] = useState({});
  const field = Field.useField();
  const [selectedIds, setSelectedIds] = useState<string[]>([]);
  const [operation, setOperation] = useState<OperationProps>();
  const [cast, setCast] = useState<CastProps>();

  const { data, loading, request: sRequest } = useRequest(
    () => ({
      url: '/api/screen',
      params: {
        limit,
        skip: (page - 1) * limit,
        ...filter,
        ...sort,
      },
    }),
    {
      manual: false,
      refreshDeps: [page, sort, filter],
    },
  );

  const onDelete = (_ids: string[]) => {
    return () => {
      Dialog.confirm({
        title: '删除提醒',
        content: `确定要删除 ${_ids.length} 个设备吗？`,
        onOk: async () => {
          try {
            await request.delete('/api/screen', { data: { _ids } });
            sRequest();
            Message.success('删除成功');
          } catch (e) {
            Message.error('网络错误');
          }
        },
      });
    };
  };

  return (
    <>
      <Card free>
        <Card.Content>
          <Box padding={10}>
            <Form responsive fullWidth labelAlign="top" field={field}>
              <Form.Item colSpan={3} label="设备名称">
                <Input name="name" placeholder="输入设备名称进行搜索" />
              </Form.Item>
              <Form.Item colSpan={3} label="城市">
                <Input name="city" placeholder="输入城市进行搜索" />
              </Form.Item>
              <Form.Item colSpan={3} label="学校">
                <Input name="school" placeholder="输入学校进行搜索" />
              </Form.Item>
              <ResponsiveGrid.Cell colSpan={3} className={styles.btns}>
                <Box spacing={8} direction="row" align="flex-end" justify="center" style={{ height: '100%' }}>
                  <Button
                    type="primary"
                    onClick={() => {
                      setPage(1);
                      setFilter(field.getValues());
                    }}
                  >
                    查询
                  </Button>
                  <Form.Reset>重置</Form.Reset>
                </Box>
              </ResponsiveGrid.Cell>
            </Form>
          </Box>
          <Divider dashed />
          <div className={styles.Main}>
            <Loading visible={loading} style={{ display: 'block' }}>
              <div className={styles.add}>
                <Button
                  type="primary"
                  onClick={() => {
                    setOperation({ action: 'add', item: {} });
                  }}
                >
                  新增
                </Button>
                <Button type="primary" disabled={!selectedIds.length} onClick={onDelete(selectedIds)}>
                  删除
                </Button>
              </div>
              <Table
                className={styles.Table}
                hasBorder={false}
                dataSource={data?.items}
                primaryKey="_id"
                rowSelection={{
                  selectedRowKeys: selectedIds,
                  columnProps: () => ({ lock: 'left' }),
                  onChange: (ids) => {
                    setSelectedIds(ids);
                  },
                }}
                sort={{ [sort.field]: sort.order }}
                onSort={(field, order) => {
                  setPage(1);
                  setSort({ field, order });
                }}
              >
                <Table.Column title="名称" dataIndex="name" sortable />
                <Table.Column
                  title="状态"
                  dataIndex="status"
                  sortable
                  cell={(v: number, i: number, r: any) => (
                    <>
                      {v === 1 ? (
                        <Tag color="green" size="small">
                          在线
                        </Tag>
                      ) : (
                        <Tag color="red" size="small">
                          离线
                        </Tag>
                      )}
                      <Icon
                        className={styles.cursor}
                        type="refresh"
                        onClick={async () => {
                          await request.put(`/api/screen/${r._id}`, { sn: r.sn });
                          sRequest();
                        }}
                      />
                    </>
                  )}
                />
                <Table.Column title="覆盖人数" dataIndex="coverage" align="center" sortable />
                <Table.Column title="地址" dataIndex="address" />
                <Table.Column
                  title="位置"
                  dataIndex="location"
                  cell={(v: any) => (
                    <>
                      <div>经 {v.coordinates[0]}</div>
                      <div>纬 {v.coordinates[1]}</div>
                    </>
                  )}
                />
                <Table.Column
                  title="现场图片"
                  dataIndex="imgUrls"
                  align="center"
                  cell={(v: string[]) => v && v[0] && <img className={styles.img} src={v[0]} />}
                />
                <Table.Column
                  title="所在城市"
                  dataIndex="city"
                  align="center"
                  cell={(v: string) => v || '北京'}
                  sortable
                />
                <Table.Column title="所在学校" dataIndex="school" sortable />
                <Table.Column title="序列号" dataIndex="sn" />
                <Table.Column
                  title="已投放"
                  cell={(v: any, i: any, r: any) => (
                    <div className={styles.opt}>
                      <Button
                        type="primary"
                        text
                        onClick={() => {
                          setCast({ type: 'image', screenId: r._id });
                        }}
                      >
                        图片
                      </Button>
                      <Divider direction="ver" />
                      <Button
                        type="primary"
                        text
                        onClick={() => {
                          setCast({ type: 'video', screenId: r._id });
                        }}
                      >
                        视频
                      </Button>
                    </div>
                  )}
                />
                <Table.Column
                  title="操作"
                  cell={(v: any, i: any, r: any) => (
                    <div className={styles.opt}>
                      <Button
                        type="primary"
                        text
                        onClick={() => {
                          setOperation({ action: 'edit', item: r });
                        }}
                      >
                        编辑
                      </Button>
                      <Divider direction="ver" />
                      <Button type="primary" text onClick={onDelete([r._id])}>
                        删除
                      </Button>
                    </div>
                  )}
                />
              </Table>
              <Box margin={[15, 0, 0, 0]} direction="row" align="center" justify="space-between">
                <div className={styles.total}>共 {data?.total} 个设备</div>
                <Pagination current={page} pageSize={limit} total={data?.total} onChange={(cur) => setPage(cur)} />
              </Box>
            </Loading>
          </div>
        </Card.Content>
      </Card>
      <DialogOperation
        visible={!!operation}
        action={operation?.action}
        item={operation?.item}
        submit={async (values) => {
          try {
            if (operation?.action === 'add') {
              await request.post('/api/screen', values);
              sRequest();
              Message.success('添加成功');
            } else if (operation?.action === 'edit') {
              await request.put(`/api/screen/${operation.item._id}`, values);
              sRequest();
              Message.success('编辑成功');
            }
            setOperation(undefined);
          } catch (e) {
            Message.error('网络错误');
          }
        }}
        onClose={() => {
          setOperation(undefined);
        }}
        onCancel={() => {
          setOperation(undefined);
        }}
      />
      <DialogCast
        visible={!!cast}
        type={cast?.type}
        screenId={cast?.screenId}
        onClose={() => {
          setCast(undefined);
        }}
      />
    </>
  );
};

export default TableList;
